package com.ccb.sc.common.modules.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ccb.sc.common.bind.vo.KeyValueIconVo;
import com.ccb.sc.common.enums.ValidStatus;
import com.ccb.sc.common.modules.goods.entity.Category;
import com.ccb.sc.common.modules.goods.enums.CategoryType;
import com.ccb.sc.common.modules.goods.mapper.CategoryMapper;
import com.ccb.sc.common.modules.goods.service.ICategoryService;
import com.ccb.sc.common.modules.goods.utils.TreeCategoryUtil;
import com.ccb.sc.common.modules.goods.vo.CategoryTreeVo;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 产品分类 服务实现类
 * </p>
 *
 * @author ken
 * @since 2020-08-21
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Override
    public List<KeyValueIconVo> findAll(Long parentId, Long type) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Category::getStatus, ValidStatus.VALID);
        queryWrapper.lambda().eq(Category::getType, type);
        if (parentId != null) {
            queryWrapper.lambda().eq(Category::getParentId, parentId);
        }
        List<Category> list = this.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            return Lists.newArrayList();
        }
        return list.stream().map(item -> {
            KeyValueIconVo vo = new KeyValueIconVo();
            vo.setKey(item.getId());
            vo.setValue(item.getName());
            vo.setIcon(item.getIcon());
            vo.setParentId(item.getParentId());
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<CategoryTreeVo> getAllCategoryTree(Integer type) {
        //获取有效的分类列表
        List<Category> categories = this.list(new QueryWrapper<Category>()
                .lambda()
                .eq(Category::getType, CategoryType.getByValue(type))
                .eq(Category::getStatus, ValidStatus.VALID));
        //转换
        return TreeCategoryUtil.convertToTreeResource(categories, false);
    }
}
